<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>{{titles}}</span>
    </div>
    <el-form ref="putformRef" :model="putform" :rules="putformroles" label-width="100px">
      <el-form-item label="学科" prop="subjectID">
        <el-select v-model="putform.subjectID" placeholder="请选择" class="daaiv">
          <el-option v-for="item in subjectform" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录" prop="catalogID">
        <el-select placeholder="请选择" class="daaiv" v-model="putform.catalogID" @focus="togetcatalogID">
          <el-option v-for="item in enterpriseferm" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业" prop="enterpriseID">
        <el-select v-model="putform.enterpriseID" placeholder="请选择" class="daaiv" @focus="togetenterpriseID">
          <el-option v-for="item in erpriseIDlists" :key="item.id" :label="item.company" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-select v-model="putform.province" placeholder="请选择" @change="tochanfeper">
          <el-option v-for="(item,index) in getprovince" :key="index" :label="item" :value="item"></el-option>
        </el-select>
        <el-select v-model="putform.city" placeholder="请选择" @focus="togetcity">
          <el-option v-for="(item,index) in togetcitys" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="方向" prop="direction">
        <el-select v-model="putform.direction" placeholder="请选择" class="daaiv">
          <el-option v-for="(item,index) in direction" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型" prop="questionType">
        <el-radio v-for="item in questionType" @change="tochangequest" :key="item.value" v-model="putform.questionType" :label="item.value">{{item.label}}</el-radio>
      </el-form-item>
      <el-form-item label="难度" prop="difficulty">
        <el-radio v-for="item in difficulty" :key="item.value" v-model="putform.difficulty" :label="item.value">{{item.label}}</el-radio>
      </el-form-item>
      <el-form-item label="题干" prop="question">
        <quill-editor v-model="putform.question"></quill-editor>
      </el-form-item>
      <!-- 选项 -->
      <el-form-item label='选项' v-if="putform.questionType !==3">
        <template v-if='putform.questionType ===1'>
          <div class="option_item" v-for="(item,index) in putform.options" :key="index">
            <el-radio @change="toChange(index)" :label="true" v-model="item.isRight">{{item.code}}</el-radio>
            <el-input class="inputmax" v-model="item.title"></el-input>
            <el-upload class="avatar-uploader roupload" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="(a,b)=>handleAvatarSuccess(a, b, index)" :before-upload="beforeAvatarUpload">
              <img v-if="item.img" :src="item.img" class="avatar">
              <div v-else class="touploaddefaultimg ">上传图片</div>
              <i class="el-icon-circle-close close-toadd"></i>
            </el-upload>
          </div>
          <el-button disabled type="danger" size="mini">+增加选项与答案</el-button>
        </template>
        <template v-if='putform.questionType ===2'>
          <div class="option_item" v-for="(item,index) in putform.options" :key="index">
            <el-checkbox v-model="item.isRight" :value='! item.isRight'>{{item.code}}</el-checkbox>
            <el-input class="inputmax" v-model="item.title"></el-input>
            <el-upload class="avatar-uploader roupload" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="(a,b)=>handleAvatarSuccess(a, b, index)" :before-upload="beforeAvatarUpload">
              <img v-if="item.img" :src="item.img" class="avatar">
              <div v-else class="touploaddefaultimg ">上传图片</div>
              <i class="el-icon-circle-close close-toadd"></i>
            </el-upload>
          </div>
          <el-button :disabled='todisabled' @click="toaddoption" type="danger" size="mini">+增加选项与答案</el-button>
        </template>

      </el-form-item>

      <!-- 解析视频 -->
      <el-form-item label='解析视频' prop="videoURL">
        <el-input class="daaiv" v-model="putform.videoURL"></el-input>
      </el-form-item>
      <el-form-item label='答案解析' prop="answer">
        <quill-editor v-model="putform.answer"></quill-editor>
      </el-form-item>
      <el-form-item label="题目备注" prop="remarks">
        <el-input type="textarea" v-model="putform.remarks"></el-input>
      </el-form-item>
      <el-form-item label='试题标签'>
        <el-select multiple filterable allow-create default-first-option placeholder="请选择试题标签" class="daaiv" v-model="putform.tags" @focus="togettagsID">
          <el-option v-for="item in tagslist" :key="item.value" :label="item.label" :value="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="tosubmit">{{submits}}</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 导入题型 //导入难度 //导入方向
import { questionType, difficulty, direction } from '../../api/hmmm/constants'
// 导入学科
import { simple } from '../../api/hmmm/subjects'
// //导入目录
import { simple as dirsimple } from '../../api/hmmm/directorys'
// 获取城市列表
import { provinces, citys } from '../../api/hmmm/citys'
// 获取企业信息
import { list as erpriseIDlist } from '../../api/hmmm/companys'
// 导入标签
import { simple as tagssimple } from '../../api/hmmm/tags'
// 添加列表
import { add as questionaddnowlist, detail as getquestionidlist, update as updatequestionlist } from '../../api/hmmm/questions'
export default {
  name: 'questions-new',
  data () {
    return {
      // 是否禁用添加
      todisabled: true,
      // 题型
      questionType: { ...questionType },
      // 难度
      difficulty: { ...difficulty },
      // 方向
      direction: [...direction],
      // 学科列表
      subjectform: [],
      // 获取目录列表
      enterpriseferm: [],
      // 获取城市县
      togetcitys: [],
      // 获取企业数据列表
      erpriseIDlists: [],
      // 查询参数
      p: {
        page: 1,
        pagesize: 10
      },
      // 获取标签数据
      tagslist: [],
      putform: {
        number: '',
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        question: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: '',
        isPerfect: ''
      },
      // 表单验证
      putformroles: {
        subjectID: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        catalogID: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        enterpriseID: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        province: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        city: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        direction: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        questionType: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        difficulty: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        question: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        videoURL: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        answer: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }],
        remarks: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }]
      },
      // 添加选项的个数
      count: 0,
      // 输入类型
      type: '1'
    }
  },

  created () {
    this.togetsimple()
    this.Backfill()
  },
  methods: {
    // 看看是否回填数据
    async Backfill () {
      if (!this.$route.query.id) return
      const id = this.$route.query.id
      // const id = 23

      this.type = '2'
      const ret = await getquestionidlist({ id: id, isNext: false })
      if (ret.status === 200) {
        console.log(ret.data)
        // 修改类型
        ret.data.questionType = parseInt(ret.data.questionType)
        // 修改难度
        ret.data.difficulty = parseInt(ret.data.difficulty)
        // 修改标签
        ret.data.tags = ret.data.tags.split(',')
        // 修改选项
        ret.data.options = this.toisright(ret.data.options)
        // 修改企业--不用改之前看错了
        // ret.data.enterpriseID = ret.data.creatorID
        // 覆盖数据
        this.putform = ret.data
        // 判断是否为多选类型
        if (this.putform.questionType === 2) {
          this.todisabled = false
        }
        // console.log(ret.data)
        // console.log(this.putform)
        this.$nextTick(() => {
          // 立刻调用获取目录数据
          this.togetcatalogID()
          // 立刻调用获取企业数据
          this.togetenterpriseID()
        })

        // 不管
        // ret.data.catalogID = String(ret.data.catalogID)
        // ret.data.enterpriseID = Number(ret.data.enterpriseID)
      }
    },
    // 获取学科数据
    async togetsimple () {
      try {
        const ret = await simple(this.p)
        if (ret.status === 200) {
          this.subjectform = ret.data
        } else {
          this.$message.error('获取课程列表失败')
        }
      } catch {
        this.$message.error('获取课程列表失败')
      }
    },
    // 获取对应目录数据
    async togetcatalogID () {
      try {
        if (!this.putform.subjectID) return
        const ret = await dirsimple(this.putform.subjectID)

        if (ret.status === 200) {
          this.enterpriseferm = ret.data
        } else {
          this.$message.error('获取目录数据失败')
        }
      } catch {
        this.$message.error('获取目录数据失败')
      }
    },
    // 改变市-县清空
    tochanfeper () {
      this.putform.city = ''
    },
    // 添加图片上传
    handleAvatarSuccess (res, file, index) {
      console.log(res, file, index)
      this.putform.options[index].img = URL.createObjectURL(file.raw)
    },
    // 判断上传的图片要求
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 获取标签数据
    async togettagsID () {
      if (!this.putform.subjectID) return
      try {
        const ret = await tagssimple({ ...this.p, subjectID: this.putform.subjectID })
        if (ret.status === 200) {
          this.tagslist = ret.data
        } else {
          this.$message.error('获取标签数据失败')
        }
      } catch {
        this.$message.error('获取标签数据失败')
      }
    },
    // 获取企业信息
    async togetenterpriseID () {
      if (!this.putform.province) return
      if (!this.putform.city) return
      try {
        const ret = await erpriseIDlist({
          ...this.p
        })
        if (ret.status === 200) {
          console.log(ret.data.items)
          this.erpriseIDlists = ret.data.items
        } else {
          this.$message.error('获取企业数据失败')
        }
      } catch {
        this.$message.error('获取企业数据失败')
      }
    },
    // 点击确定添加
    tosubmit () {
      this.$refs.putformRef.validate(async valid => {
        if (!valid) return this.$message.error('验证失败')
        if (!this.putform.question) return this.$message.error('题干不能为空')
        if (!this.putform.answer) return this.$message.error('答案解析不能为空')
        // 调取接口获取数据
        this.putform.questionType = String(this.putform.questionType)
        this.putform.difficulty = String(this.putform.difficulty)

        this.putform.tags = this.putform.tags.join('-')
        console.log(this.putform)
        try {
          if (this.type === '1') {
            const ret = await questionaddnowlist(this.putform)
            if (ret.status === 200) {
              this.$message.success('添加成功')
              // 清空数据
              // 清空效果
              this.$refs.putformRef.resetFields()
              this.putform = this.$options.data().putform
              this.$router.push('/questions/list')
            } else {
              this.$message.error('添加失败')
            }
          } else {
            const ret = await updatequestionlist(this.putform)
            if (ret.status === 200) {
              this.$message.success('修改成功')
              // 清空数据
              // 清空效果
              this.$refs.putformRef.resetFields()
              this.putform = this.$options.data().putform
              this.$router.push('/questions/list')
              this.type = this.$options.data().type
            } else {
              this.$message.error('添加失败')
            }
          }
        } catch {
          this.$message.error('添加失败')
        } finally {
          // 清空路由查询参数
          this.$route.query.id = ''
        }
      })
    },
    // 得到他的城市
    togetcity () {
      if (!this.putform.province) return
      this.togetcitys = citys(this.putform.province)
    },
    // 单选框排他
    toChange (n) {
      this.putform.options.forEach(item => {
        item.isRight = false
      })
      this.putform.options[n].isRight = true
    },
    // 重置选项--类型控制选项
    tochangequest () {
      this.putform.options = this.$options.data().putform.options
      if (this.putform.questionType === 2) {
        this.todisabled = false
      } else {
        this.todisabled = true
        this.putform.options = this.$options.data().putform.options
        this.count = 0
      }
    },
    // 添加选项
    toaddoption () {
      const arr = ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q']
      this.putform.options.push({
        isRight: false, code: arr[this.count], title: '', img: ''
      })
      this.count++
    },
    // 回填点击选项属性
    toisright (n) {
      const arr = []
      n.forEach(item => {
        const row = {}
        for (const i in item) {
          if (i === 'isRight') {
            row[i] = item[i] !== 0
          } else {
            row[i] = item[i]
          }
        }
        arr.push(row)
      })
      return this.sort(arr)
    },
    // 返回数据的选项排序按id--冒泡排序
    sort (arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {
          if (arr[j].id > arr[j + 1].id) { // 相邻元素两两对比
            var hand = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = hand
          }
        }
      }
      return arr
    }

  },
  computed: {
    // 获取城市
    getprovince () {
      return provinces()
    },
    // 标题
    titles () {
      if (this.type === '1') {
        return '试题录入'
      } else {
        return '重新录入'
      }
    },
    // 提交名字
    submits () {
      if (this.type === '1') {
        return '确定添加'
      } else {
        return '确定修改'
      }
    }
  }

}
</script>

<style scoped lang='scss'>
.box-card {
  width: 100%;
  // 设置富文本编辑器的默认最小高度
  ::v-deep .ql-editor {
    min-height: 150px;
  }

  .option_item {
    width: 500px;
    height: 100px;
    .inputmax {
      width: 300px;
      height: 36px;
      line-height: 80px;
    }
    .roupload {
      width: 100px;
      height: 60px;
      line-height: 70px;
      float: right;
      margin-right: 30px;
    }
    .touploaddefaultimg {
      line-height: 70px;
      font-size: 10px;
      width: 110px;
      height: 70px;

      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .close-toadd {
      position: relative;
      font-size: 18px;
      transform: translate(320%, -600%);
    }
  }
}
.daaiv {
  width: 500px;
}
.avatar-uploader .el-upload {
  border: 1px solid #d40c0c;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar {
  width: 100px !important ;
  height: 60px !important;
}
</style>
